<?php
/**
 * Created by PhpStorm.
 * User: zouhua
 * Date: 2017/4/26
 * Time: 20:16
 */

namespace app\controllers;


use app\components\WebController;
use app\models\Activity;
use app\models\ActivityApply;
use app\models\Favorite;
use app\models\Like;
use Yii;

class ActivityController extends WebController {

    public function actionApply() {
        $id = intval($this->get('id'));
        $model = Activity::findOne($id);
        if (!$model) {
            return $this->error('网络异常');
        }
        if (!$model->getIsPending()) {
            return $this->error('报名已结束');
        }
        if (Yii::$app->user->isGuest) {
            return $this->error('请先登录');
        }
        if (!$this->user->getIsStudent()) {
            return $this->error('只有学生可以报名');
        }
        if (empty($this->user->profile->school) || empty($this->user->phone)) {
            return $this->error('请完善个人资料后在报名');
        }
        if (!$model->getIsApply($this->user, FALSE)) {
            return $this->error('非法操作');
        }
        return ActivityApply::saveApply($model, $this->user);
    }

    public function actions() {
        return [
            'index' => [
                'class' => 'app\actions\ActivityIndexAction',
                'modelClass' => Activity::className()
            ],
            'like' => [
                'class' => 'app\actions\LikeAction',
                'modelClass' => Activity::className(),
                'own' => Like::OWN_ACTIVITY
            ],
            'comments' => [
                'class' => 'app\actions\ActivityCommentAction'
            ]
        ];
    }

    public function actionDetail() {
        $id = intval($this->get('id'));
        $model = Activity::findOne($id);
        if (!$model) {
            return $this->redirect(["{$this->id}/"]);
        }

        $model->views = $model->views + 1;
        $model->save(FALSE);

        $favoriteClass = Favorite::getIsFavorite($this->user, $id);
        $isApply = $model->getIsApply($this->user);
        $isLike = Like::getIsLike(Like::OWN_ACTIVITY, $id, $this->getLikeId());

        $this->view->title = $model->title;
        $user = $this->user;
        $this->layout = 'detail';
        return $this->render(compact('model', 'user', 'favoriteClass', 'isApply', 'isLike'));
    }
}